package com.iflytek.uoamp.notify.wechat.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.CharBuffer;

import org.slf4j.Logger;

import com.iflytek.uoamp.common.notify.util.LogbackInstance;

/**
 * 文件操作类
 * 
 * @desc: sendwx
 * @author: lwsong@iflytek.com
 * @createTime: 2016年6月30日 下午2:34:53
 * @history:
 * @version: v1.0
 */
public class FileUtils {
	
	  private static final Logger logger = LogbackInstance.getInstance().getLogger(FileUtils.class);
	/**
	 * 将字符串写入文件
	 * 
	 * @param content
	 * @param path
	 * @author: lwsong@iflytek.com
	 * @throws IOException
	 * @createTime: 2016年6月30日 下午2:35:46
	 * @history:
	 */
	@SuppressWarnings("resource")
	public static void writStrToFile(String content, String path,
			String fileName) {
		FileOutputStream fos = null;
		OutputStreamWriter out = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path + "/" + fileName + ".txt");
			if (!file.exists()) {
				file.createNewFile();
			}else{
				file.delete();
				file.createNewFile();
			}
			fos = new FileOutputStream(file, false);
			out = new OutputStreamWriter(fos, "utf-8");
			bw = new BufferedWriter(out);
			bw.write(content);
			bw.write("\r\n");
			bw.flush();
			bw.close();
		} catch (IOException e) {
			logger.error("writStrToFile exception ===================="+e.getMessage(),e);
		}finally{
			try {
				if(fos != null){
					fos.close();
				}	
			} catch (IOException e2) {
				logger.error("close fos exception =================="+e2.getMessage(), e2);
			}
		}
			
	}

	/**
	 * 读取文件
	 * 
	 * @param path
	 * @param fileName
	 * @return
	 * @throws IOException
	 * @author: lwsong@iflytek.com
	 * @createTime: 2016年6月30日 下午2:41:14
	 * @history:
	 */
	@SuppressWarnings("resource")
	public static String readFromFile(String path, String fileName){
		FileReader fReader = null;
		try {
			String text = "";
			File file = new File(path + '/' + fileName + ".txt");
			if (!file.exists()) {
				file.createNewFile();
			}
			CharBuffer cbuf = null;
		    fReader = new FileReader(file);
			cbuf = CharBuffer.allocate((int) file.length());
			fReader.read(cbuf);
			text = new String(cbuf.array());
			return text;
		} catch (IOException  e) {
			logger.error("readFromFile io exception ================"+e.getMessage(), e);
		}finally{
			try {
				if(fReader != null){
					fReader.close();
				}
			} catch (IOException e2) {
				logger.error("close stream exception ================="+e2.getMessage(), e2);
			}
		}	
		return "";	
	}
	
}
